
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../api/UserApi.dart';
import '../../utils/JpushUtil.dart';
import '../../utils/SPutil.dart';
import '../../utils/Settings.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import '../../utils/Utils.dart';


class UserLoginPage extends StatefulWidget {
  const UserLoginPage({super.key});

  @override
  State<UserLoginPage> createState() => _UserLoginState();
}

class _UserLoginState extends State<UserLoginPage> with SingleTickerProviderStateMixin {
  int _flag = 0;
  bool isCheck = false;
  late String jpushId;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    accountNoController.dispose();
    pwdController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Settings.backgroundColor,

        body:  WillPopScope(
          onWillPop: () async{
            _flag ^= 1;
            Future.delayed(const Duration(seconds: 2), () => _flag = 0);
            EasyLoading.showToast("再按一次退出");
            return _flag == 0;
          },
          child: SingleChildScrollView(
            child: Stack(
              clipBehavior: Clip.none,
              children: [
                SizedBox(
                  height:MediaQuery.of(context).size.height,
                  width: MediaQuery.of(context).size.width,
                  child: Image.asset("images/logo_bg.png",fit: BoxFit.fill,),
                ),
                Center(
                  child: Padding(
                    padding: const EdgeInsets.only(top: 160),
                    child: Column(
                      mainAxisSize: MainAxisSize.max,//表示Row在主轴(水平)方向占用的空间，默认是MainAxisSize.max，表示尽可能多的占用水平方向的空间，
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Image.asset("images/zhongfu-logo.png",width: 200,height:100,),
                        Container(
                          alignment: Alignment.center,
                          padding: const EdgeInsets.only(top:80,left:30.0,right: 30.0),
                          margin: const EdgeInsets.only(bottom: 10.0),
                          child: Container(
                            child: buildForm(),
                          ),
                        ),


                      ],
                    )
                  ),
                )
              ],
            ),
          ),

        )

    );
  }


  /* 定义两个container类 unameController和pwdController*/
  TextEditingController accountNoController = TextEditingController();
  TextEditingController pwdController = TextEditingController();
  GlobalKey formKey = GlobalKey<FormState>();
  Widget buildForm(){
    return Form(
      key: formKey,

      child: Column(
        children: [
          TextFormField(
            autofocus: false,
            keyboardType: TextInputType.visiblePassword, //键盘输入类型(七种类型)
            textInputAction: TextInputAction.next, //键盘动作按钮图标
            controller: accountNoController, //container
            decoration: const InputDecoration(
              labelText: "账号",
              hintText: "请输入账号",
              icon: Icon(Icons.person),
            ),
            onChanged:(v){ //监听输入框值变化
              /*print("$v");*/
            },
            validator: (v){
              if(v==null || v.isEmpty || v.trim().isEmpty){
                return '请输入账号';
              }
            },

          ),
          TextFormField(
            autofocus: false,
            controller: pwdController,
            obscureText: true, //密码输入类型
            decoration: const InputDecoration(
                labelText: "密码",
                hintText: "请输入密码",
                icon: Icon(Icons.lock)
            ),
            validator: (v){
              if(v==null || v.isEmpty || v.trim().isEmpty){
                return '请输入密码';
              }
            },
          ),

          Padding(
              padding: const EdgeInsets.only(top: 40.0),
              child: Row(
                children: [
                  Expanded(
                  child:SizedBox(
                    height: 50,
                    width: MediaQuery.of(context).size.width * 0.95,
                    child: OutlinedButton(
                      style: ButtonStyle(
                        backgroundColor: MaterialStateProperty.resolveWith<Color>((states) {
                          return Settings.primaryColor;
                        }),
                        foregroundColor: MaterialStateProperty.resolveWith<Color>((states) {
                          return Colors.white;
                        }),
                      ),
                      onPressed:submit,
                      child: const Text('登录',style: TextStyle(fontSize: 17,)),
                    ),
                  )

                  )
                ],
              )
          ),
          // Row(
          //   mainAxisAlignment: MainAxisAlignment.center,
          //   children: [
          //     Checkbox(
          //       activeColor: Settings.primaryColor,
          //       side: const BorderSide(color: Color.fromRGBO(194, 194, 194, 1)),
          //       value: isCheck,
          //       onChanged: (v){
          //         setState(() {
          //           isCheck = v!;
          //         });
          //       },
          //     ),
          //     Wrap(
          //       children: [
          //         const Text("我已阅读并同意",style: TextStyle(color: Colors.grey),),
          //         InkWell(
          //           onTap: ()async{
          //
          //           },
          //           child: const Text("用户协议",style: TextStyle(color: Colors.blue),),
          //         ),
          //         const Text("和",style: TextStyle(color: Colors.grey)),
          //         InkWell(
          //           onTap: ()async{
          //
          //           },
          //           child: const Text("隐私政策",style: TextStyle(color: Colors.blue),),
          //         ),
          //       ],
          //     )
          //   ],
          // ),
        ],
      ),
    );
  }

  getJpushId()async{
    jpushId = await JpushUtil.getInstance().getRegistrationID();
  }


  submit() async {
    // if(!isCheck){
    //   EasyLoading.showInfo("请先阅读和同意用户协议和隐私政策");
    //   return;
    // }
    ///获取极光的推送ID
    // await getJpushId();
    if((formKey.currentState as FormState).validate()){
      EasyLoading.show(status: "登录中...");
      Map formData={"accountNo":accountNoController.text,"empPwd":Utils.generateMD5(pwdController.text)};
      dynamic res =  await UserApi.login(formData);
      if(res["success"]){
        EasyLoading.dismiss();

        //否则会有 DON'T use BuildContext across asynchronous gaps. 警告
        if(mounted){
          if(res["result"]["isDefaultPwd"]!=null && res["result"]["isDefaultPwd"]){
            Get.toNamed("/changeDefaultPwdPage",arguments: {"accountNo":accountNoController.text});
          }else{
            ///token 放入本地缓存
            SPutil.setLocalStorage(Settings.localStorageKeys["token"], res["result"]["token"]);
            Get.offAllNamed("/");
          }

        }

      }else{
        EasyLoading.dismiss();
        EasyLoading.showError(res["message"]);
      }
    }
  }
}


